package com.application;

import java.util.concurrent.TimeUnit;

import okhttp3.OkHttpClient;
import okhttp3.logging.HttpLoggingInterceptor;
import retrofit2.Retrofit;
import retrofit2.adapter.rxjava3.RxJava3CallAdapterFactory;
import retrofit2.converter.gson.GsonConverterFactory;

public class RetrofitRxJavaClient {

    private static final String BASE_URL="https://jsonplaceholder.typicode.com/";

//    单例模式
    private static RetrofitRxJavaClient instance;
    private final RetrofitInterface apiService;

    public RetrofitRxJavaClient() {
        OkHttpClient.Builder okHttpBuilder = new OkHttpClient.Builder();

//        日志拦截器
        HttpLoggingInterceptor loggingInterceptor=new HttpLoggingInterceptor();
        loggingInterceptor.setLevel(HttpLoggingInterceptor.Level.BODY);
        okHttpBuilder.addInterceptor(loggingInterceptor);

//        设置超时
        okHttpBuilder.connectTimeout(10, TimeUnit.SECONDS);
        okHttpBuilder.readTimeout(10,TimeUnit.SECONDS);
        okHttpBuilder.writeTimeout(10,TimeUnit.SECONDS);

        Retrofit retrofit=new Retrofit.Builder()
                .baseUrl(BASE_URL)
                .client(okHttpBuilder.build())
                .addConverterFactory(GsonConverterFactory.create())
                .addCallAdapterFactory(RxJava3CallAdapterFactory.create())
                .build();

        this.apiService =retrofit.create(RetrofitInterface.class);
    }

//    单例获取方法
    public static synchronized RetrofitRxJavaClient getInstance(){
        if (instance==null){
            instance=new RetrofitRxJavaClient();
        }
        return instance;
    }

//    对外提供接口实例
    public RetrofitInterface getApiService() {
        return apiService;
    }
}
